﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm.ApiServer;
using System.ComponentModel;
using System.Data.Entity;
using com.nm.ApiServer.Attributes;
using george.Data;
using com.nm.Attributes;
using CsrdAPI.model;
using EntityFramework.Extensions;
using com.nm.db.Models.Systems;
using com.nm.Helper;
using CsrdAPI.Csrd;

namespace CsrdAPI
{
    [Description("客户资料管理")]
    public class CsrdClientHandler : BaseHandler
    {
        [MustLogin]
        [Description("获取客户列表")]
        [ReturnType(typeof(PaperData<CsrdClient>))]
        public ApiResult GetCsrdClientList(
            [ParamDescription("内部店铺信息")] string CodeOrName = "",
            [ParamDescription("合同开始时间")] DateTime BeginDate = default(DateTime),
            [ParamDescription("合同结束时间")] DateTime EndDate = default(DateTime),
            [ParamDescription("页码")] int Page = 1,
            [ParamDescription("页数")] int Size = 10)
        {
            var dc = new CsrdEntities();
            var query = (from c in dc.Csrd_Client
                         join u in dc.Csrd_vm_user on c.Operator equals u.UserID
                         select new
                         {
                             c,
                             u.UserName,
                             img = (dc.vm_CsrdClient.FirstOrDefault(t => t.ID == c.RigistImgID))
                         });
            if (!string.IsNullOrWhiteSpace(CodeOrName))
            {
                query = query.Where(t => t.c.ShopCode.Contains(CodeOrName) || t.c.ShopName.Contains(CodeOrName));
            }
            if (BeginDate != default(DateTime))
            {
                query = query.Where(t => t.c.ContractBeginDate >= BeginDate);
            }
            if (EndDate != default(DateTime))
            {
                query = query.Where(t => t.c.ContractEndDate <= EndDate);
            }
            var result = PaperData<CsrdClient>.Create(query.Count(), Size, Page);
            result.Items = query.OrderByDescending(t => t.c.CreateDate).Skip(result.Skip).Take(result.Limt).ToList().Select(o => new CsrdClient
            {
                ClientID = o.c.ClientID,
                ClientCode = o.c.ClientCode,
                ShopID = o.c.ShopID,
                ShopCode = o.c.ShopCode,
                ShopName = o.c.ShopName,
                RegistName = o.c.RegistName,
                RegistCode = o.c.RegistCode,
                RedistAddress = o.c.RedistAddress,
                BankName = o.c.BankName,
                AccountCode = o.c.AccountCode,
                ShopLinkMan = o.c.ShopLinkMan,
                ShopTelePhone = o.c.ShopTelePhone,
                ContractBeginDate = Convert.ToDateTime(o.c.ContractBeginDate),
                ContractEndDate = Convert.ToDateTime(o.c.ContractEndDate),
                Discount = Convert.ToDouble(o.c.Discount),
                RigistImgID = o.c.RigistImgID,
                //  ImgUrl = Request.GetResolveImageUrl(o.img==null?"":o.img.Url,"http"),
                ImgUrl = o.img == null ? "" : Request.GetImageUrl(o.img.Url, "http"),
                ContractCode = o.c.ContractCode,
                ContractState = o.c.ContractState,
                Operator = o.UserName
            }).ToList();
            return Success(result);
        }

        [MustLogin]
        [Description("获取客户详情")]
        [ReturnType(typeof(CsrdClient))]
        public ApiResult GetID([ParamDescription("内部店铺信息")]string ShopID)
        {
            var dc = new CsrdEntities();
            var query = (from c in dc.Csrd_Client
                         where c.ShopID == ShopID
                         select new
                         {
                             c,
                             img = (dc.vm_CsrdClient.FirstOrDefault(t => t.ID == c.RigistImgID))
                         }).FirstOrDefault();
            if (query == null) return Error("未找到数据");
            var result = new CsrdClient
            {
                ClientID = query.c.ClientID,
                ClientCode = query.c.ClientCode,
                ShopID = query.c.ShopID,
                ShopCode = query.c.ShopCode,
                ShopName = query.c.ShopName,
                RegistName = query.c.RegistName,
                RegistCode = query.c.RegistCode,
                RedistAddress = query.c.RedistAddress,
                BankName = query.c.BankName,
                AccountCode = query.c.AccountCode,
                ShopLinkMan = query.c.ShopLinkMan,
                ShopTelePhone = query.c.ShopTelePhone,
                ContractBeginDate = Convert.ToDateTime(query.c.ContractBeginDate),
                ContractEndDate = Convert.ToDateTime(query.c.ContractEndDate),
                Discount = Convert.ToDouble(query.c.Discount),
                RigistImgID = query.c.RigistImgID,
                ImgUrl = query.img == null ? "" : Request.GetImageUrl(query.img.Url, "http"),
                ContractCode = query.c.ContractCode,
                ContractState = query.c.ContractState
            };
            return Success(result);
        }

        [JsonType]
        [MustLogin]
        [Description("新增")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Create([ParamDescription("输入参数")] CsrdClient param)
        {
            if (param == null) return Error("对象为空！");
            if (string.IsNullOrWhiteSpace(param.RegistName)) return Error("注册名称不能为空！");
            if (string.IsNullOrWhiteSpace(param.ShopName)) return Error("店铺名不能为空！");
            if (string.IsNullOrWhiteSpace(param.ShopCode)) return Error("店铺编码不能为空！");
            //if (string.IsNullOrWhiteSpace(param.ShopLinkMan)) return Error("店铺店长不能为空！");
            //if (string.IsNullOrWhiteSpace(param.ShopTelePhone)) return Error("店铺电话不能为空！");
            if (string.IsNullOrWhiteSpace(param.RegistCode)) return Error("营业热量不能为空！");
            if (string.IsNullOrWhiteSpace(param.RedistAddress)) return Error("店铺注册地址不能为空！");
            if (string.IsNullOrWhiteSpace(param.BankName)) return Error("开户行不能为空！");
            if (string.IsNullOrWhiteSpace(param.AccountCode)) return Error("账号不能为空！");
            if (string.IsNullOrWhiteSpace(param.Discount.ToString())) return Error("合同扣点不能为空！");
            if (string.IsNullOrWhiteSpace(param.ContractBeginDate.ToString())) return Error("合同开始日期不能为空！");
            if (string.IsNullOrWhiteSpace(param.ContractEndDate.ToString())) return Error("合同结束日期不能为空！");

            var dc = new CsrdEntities();
            var list = dc.Cdrs_vm_shop.FirstOrDefault(p => p.shopcode == param.ShopCode)?.BigAreaName;

            var list2 = dc.Csrd_Province.Where(p => p.ProvinceName.Contains(list)).ToList()[0].Code;

            var list3 = dc.Csrd_Client.Where(p => p.ClientCode.Substring(0, 2) == list2.ToString()).Max(c => c.ClientCode);
            var TempClientCode = "";
            if (string.IsNullOrEmpty(list3))
            {
                TempClientCode = list2.ToString() + "001";
            }
            else
            {
                TempClientCode = (Convert.ToInt32(list3) + 1).ToString();
            }
            if (dc.Csrd_Client.Any(t => t.RegistName == param.RegistName)) return Error("注册名称重复！");
            if (dc.Csrd_Client.Any(t => t.ShopName == param.ShopName)) return Error("店铺名重复！");
            var add = new Csrd_Client
            {
                //ClientID自增长标识，不用插入数据
                ClientCode = TempClientCode,
                ShopID = param.ShopID,
                RegistName = param.RegistName,
                ShopName = param.ShopName,
                ShopCode = param.ShopCode,
                ShopLinkMan = param.ShopLinkMan,
                ShopTelePhone = param.ShopTelePhone,
                RegistCode = param.RegistCode,
                RedistAddress = param.RedistAddress,
                BankName = param.BankName,
                AccountCode = param.AccountCode,
                Discount = Convert.ToDecimal(param.Discount),
                ContractBeginDate = param.ContractBeginDate,
                ContractEndDate = param.ContractEndDate,
                CreateDate = DateTime.Now,
                Operator = this.UserId,
                RigistImgID = param.RigistImgID,
                ContractCode = param.ContractCode,
                ContractState = param.ContractState
            };
            try
            {
                dc.Csrd_Client.Add(add);
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }

            return Success(0);
        }

        [JsonType]
        [MustLogin]
        [Description("修改")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Modify([ParamDescription("输入参数")] CsrdClient param)
        {
            if (param == null) return Error("对象为空！");
            if (string.IsNullOrWhiteSpace(param.RegistName)) return Error("注册名称不能为空！");
            if (string.IsNullOrWhiteSpace(param.ShopName)) return Error("店铺名不能为空！");
            if (string.IsNullOrWhiteSpace(param.ShopCode)) return Error("店铺编码不能为空！");
            //if (string.IsNullOrWhiteSpace(param.ShopLinkMan)) return Error("店铺店长不能为空！");
            //if (string.IsNullOrWhiteSpace(param.ShopTelePhone)) return Error("店铺电话不能为空！");
            if (string.IsNullOrWhiteSpace(param.RegistCode)) return Error("营业热量不能为空！");
            if (string.IsNullOrWhiteSpace(param.RedistAddress)) return Error("店铺注册地址不能为空！");
            if (string.IsNullOrWhiteSpace(param.BankName)) return Error("开户行不能为空！");
            if (string.IsNullOrWhiteSpace(param.AccountCode)) return Error("账号不能为空！");
            if (string.IsNullOrWhiteSpace(param.Discount.ToString())) return Error("合同扣点不能为空！");
            if (string.IsNullOrWhiteSpace(param.ContractBeginDate.ToString())) return Error("合同开始日期不能为空！");
            if (string.IsNullOrWhiteSpace(param.ContractEndDate.ToString())) return Error("合同结束日期不能为空！");

            var dc = new CsrdEntities();

            var query = dc.Csrd_Client.FirstOrDefault(t => t.ShopID == param.ShopID);
            if (query == null) return Error("未找到相关记录");
            query.RegistName = param.RegistName;
            query.ShopName = param.ShopName;
            query.ShopCode = param.ShopCode;
            query.ShopLinkMan = param.ShopLinkMan;
            query.ShopTelePhone = param.ShopTelePhone;
            query.RegistCode = param.RegistCode;
            query.RedistAddress = param.RedistAddress;
            query.BankName = param.BankName;
            query.AccountCode = param.AccountCode;
            query.Discount = Convert.ToDecimal(param.Discount);
            query.RigistImgID = param.RigistImgID;
            query.ContractBeginDate = param.ContractBeginDate;
            query.ContractEndDate = param.ContractEndDate;
            query.ContractCode = param.ContractCode;
            query.ContractState = param.ContractState;
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [MustLogin]
        [Description("删除")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Remove([ParamDescription("公司ID")] string ShopID)
        {
            var dc = new CsrdEntities();
            if (dc.Csrd_Balance.Any(t => t.ShopID == ShopID && t.BlanceState != false))
                return Error("该公司在结算信息中被引用,无法删除!");
            dc.Csrd_Balance.Where(t => t.ShopID == ShopID && t.BlanceState == false).Delete();
            dc.Csrd_Client.Where(t => t.ShopID == ShopID).Delete();
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [MustLogin]
        [Description("店铺自动补全")]
        [ReturnType(typeof(PaperData<SearchShopName>))]
        public ApiResult GetShopBaseInfo(
            [ParamDescription("关键字")] string Keys = "")
        {
            var dc = new CsrdEntities();
            var query =
                dc.Cdrs_vm_shop.Where(t => t.shopcode != null 
                && t.BigAreaName != null 
                && t.shopname.Contains(Keys))
                    .AsNoTracking()
                    .Take(8)
                    .ToList();
            return Success(query);
        }
    }
}
